<?php
namespace app\index\controller;
use app\common\model\CardConsume;
use app\common\model\CardFans;
use app\common\model\CardLeaduser;
use app\common\model\CardMember;
use app\common\model\CardShareLog;
use app\common\model\CardShareRule;
use app\common\model\CardShareUser;
use app\common\model\CardUserGet;
use app\common\model\CardGeneral;
use app\common\model\CardPutRule;
use app\common\model\CardUserUpdate;
use app\common\model\OpenTemplate;
use app\common\model\WxOpen;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\merchant\controller\Qrcodes;
use app\common\model\System;
use think\Controller;
use think\Session;
use Wechat\Wxobjopen;

class Testcard extends Controller
{

    //审核卡券
    public function cardpass($datas){
        $data['notpass'] = $datas['notpass'];
        $data['notpassinfo'] = $datas['notpassinfo'];
        $CardMember = new CardMember();
        $CardMember->save($data,['card_id'=>$datas['card_id']]);
    }

    //审核门店
    public function storepass($datas){
        $map['top_mid'] = $datas['sid'];
        $map['poi_id'] = $datas['poi_id'];
        if ($datas['result'] == 'succ'){
            $data['pass_statu'] = 1;
        }else{
            $data['pass_statu'] = 3;
        }
        $data['pass_res'] = $datas['result'];
        $data['pass_msg'] = $datas['pass_msg'];
        $Merchant = new Merchant();
        $Merchant->save($data,$map);
    }

    //领取
    public function usergetcard($datas){
        $map['card_id'] =  $datas['CardId'];
        $data = $this->getdata($datas);
        //实例化模型
        $CardMember = new CardMember();
        $CardUserget = new CardUserGet();
        //获取data数据
        $data['card_type'] = $this->gettype($map);          //卡券类别
        //不是该平台创建的卡则结束该方法
        if (empty($data['card_type'])){
            exit();
        }
        //       $data['qrcode'] = $this->qrcode($datas['usercardcode']);                        //赋值data数据二维码
        //领取为会员卡则获取激活状态
        if ($data['card_type'] == 'MEMBER_CARD'){
            $activate = $CardMember->where($map)->value('activate');                 //获取本会员卡的激活状态
            $data['fire'] = $activate == 1 ? 1 : 0;                                         //判断该张会员卡是否自动激活 如果是则将领取状态改为激活   1/0
            $data['mid'] = $this->getmid($map['card_id']);
            $data['top_mid'] = $this->gettopmid($map['card_id']);
            if($data['have'] == 1){                     //判断是否为找回操作
                $map['code'] = $data['code'];
                $dataz['have'] = 1;
                $CardUserget->where(['card_id'=>$data['card_id'],'openid'=>$data['openid']])->update($dataz);                    //如果是找回则更新数据   isbackcard  1/0  找回和领取
            }
            if($data['have'] == 0){
                $code = $datas['UserCardCode'];
                $data['qrcode'] = $this->qrcode($code);
                $data['have'] = 1;
                $CardUserget->allowField(true)->save($data);            //新增则存入数据
                //分享奖励
                $share['card_id'] = $data['card_id'];
                $share['outerstr'] = $data['outerstr'];
                $share['get_code'] = $data['code'];
                $share['get_openid'] = $data['openid'];
                $share['mid'] = $data['mid'];
                $share['top_mid'] = $data['top_mid'];
                $share['type'] = 'getcard';
                $share = $this->shareget($share);
            }
        }else{
            //卡券数据存入表
            $data['have'] = 1;
            $data['top_mid'] = $this->gettopmid($map['card_id']);
            $data['mid'] = $this->getmid($map['card_id']);
            $data['fire'] = 1;
            $CardUserget->allowField(true)->save($data);
        }

    }

    //领取字段处理
    public function getdata($datas){
        if (isset($datas['FromUserName'])){
            $data['openid']=$datas['FromUserName'];
        }
        if (isset($datas['CreateTime'])){
            $data['create_time']=$datas['CreateTime'];
        }
        if (isset($datas['CardId'])){
            $data['card_id']=$datas['CardId'];
        }
        if (isset($datas['UserCardCode'])){
            $data['code']=$datas['UserCardCode'];
        }
        if (isset($datas['IsGiveByFriend'])){
            $data['isgivecard']=$datas['IsGiveByFriend'];
        }
        if (isset($datas['OuterStr'])){
            $data['outerstr']=$datas['OuterStr'];
        }
        if (isset($datas['IsRestoreMemberCard'])){
            $data['have']=$datas['IsRestoreMemberCard'];
        }
        if (isset($datas['SourceScene'])){
            $data['sourec']=$datas['SourceScene'];
        }
        return $data;
    }

    //商户ID
    public function getmid($card_id){
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id'=>$card_id])->value('mid');
        if (empty($top_mid)){
            $top_mid = $CardGeneral->where(['card_id'=>$card_id])->value('mid');
            return $top_mid;
        }else{
            return $top_mid;
        }
    }

    //top_mid
    public function gettopmid($card_id){
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id'=>$card_id])->value('top_mid');
        if (empty($top_mid)){
            $top_mid = $CardGeneral->where(['card_id'=>$card_id])->value('top_mid');
            return $top_mid;
        }else{
            return $top_mid;
        }
    }

    //类别
    public function gettype($map){
        $CardMember = new CardMember();
        $type = $CardMember->where($map)->value('card_type');
        if (empty($type)){
            $CardGeneral = new CardGeneral();
            $CardGeneral->where($map)->setDec('stocks');    //库存减一
            $CardGeneral->where($map)->setInc('getsume');    //领取加1
            $type = $CardGeneral->where($map)->value('card_type');
            return $type;
        }else{
            $CardMember->where($map)->setDec('stocks');    //库存减一
            $CardMember->where($map)->setInc('getsume');    //领取加1
            return $type;
        }
    }

    //分享领取
    /*
     * 参数card_id  outerstr  openid code mid top_mid
     */
    public function shareget($arr){
        //是否有规则
        if(strpos($arr['outerstr'],'_')) {
            $CardShareRule = new CardShareRule();
            //有无规则
            $only = $CardShareRule->where(['card_id' => $arr['card_id'], 'statu' => 0, 'rule_type' => 'SHARE'])->value('id');
            if ($only) {
                $outerstr = explode('_', $arr['outerstr']);
                //领卡
                if ($arr['type'] == 'getcard') {
                    $CardShareUser = new CardShareUser();
                    $CardShareUser->where(['card_id' => $arr['card_id'], 'openid' => reset($outerstr)])->setInc('get_ren');
                    //分享记录
                    $CardShareLog = new CardShareLog();
                    $dataget['get_openid'] = $arr['get_openid'];
                    $dataget['openid'] = reset($outerstr);
                    $dataget['get_code'] = $arr['get_code'];
                    $dataget['card_id'] = $arr['card_id'];
                    $dataget['share_uid'] = $CardShareUser->where(['card_id' => $arr['card_id'], 'openid' => reset($outerstr)])->value('id');
                    $dataget['rule_id'] = $only;
                    $dataget['mid'] = $arr['mid'];
                    $dataget['top_mid'] =  $arr['top_mid'];
                    $CardShareLog->allowField(true)->save($dataget);
                }
                //激活卡
                if ($arr['type'] == 'firecard') {
                    $CardShareUser = new CardShareUser();
                    $CardShareUser->where(['card_id' => $arr['card_id'], 'openid' => reset($outerstr)])->setInc('fire_ren');
                    $ruleuser = $CardShareUser->where(['card_id' => $arr['card_id'], 'openid' => reset($outerstr)])->find();
                    $arrs['rule_id'] = $only;
                    $arrs['openid'] = $ruleuser['openid'];
                    $arrs['card_id'] = $arr['card_id'];
                    $arrs['code'] = $ruleuser['code'];
                    //奖励积分
                    $bonus = $this->getsharebonus($arrs);
                    //奖励余额
                    $balance = $this->getsharebalance($arrs);
                    $CardUserUpdate = new CardUserUpdate();
                    //更新记录
                    if (isset($bonus)) {
                        $data['add_bonus'] = $bonus['bonus'];
                    }
                    if (isset($balance)) {
                        $data['add_balance'] = $balance['add_balance'];
                    }
                    //更新记录
                    $data['mid'] = $this->getmid($arr['card_id']);
                    $data['openid'] = $ruleuser['openid'];
                    $data['record_balance'] = '分享奖励';
                    $data['record_bonus'] = '分享奖励';
                    $data['code'] = $ruleuser['code'];
                    $data['card_id'] = $arrs['card_id'];
                    $data['con_username'] = 'share';
                    $data['hx_fs'] = '分享奖励';
                    $data['type'] = 4;
                    $data['create_time'] = time();
//                $data['con_username'] = $bonus['bonus'];
//                $data['con_username'] = $bonus['bonus'];
                    $CardUserUpdate->allowField(true)->save($data);
                    //分享记录
                    $CardShareLog = new CardShareLog();
                    if (isset($bonus)) {
                        $dataget['bonus'] = $bonus['bonus'];
                    }
                    if (isset($balance)) {
                        $dataget['balance'] = $balance['add_balance'];
                    }
                    if (isset($dataget['bonus']) || isset($dataget['balance'])) {
                        $CardShareLog->allowField(true)->save($dataget, ['get_code' => $arr['get_code'], 'get_openid' => $arr['get_openid']]);
                    }
                }
            }
        }else{
            return 1;
        }
    }

    //分享领取奖励积分
    public function getsharebonus($arrs){
        $CardShareRule = new CardShareRule();
        $ruleinfo = $CardShareRule->where(['id'=>$arrs['rule_id']])->find();
        if ($ruleinfo['reward_bonus'] > 0){
            $data['card_id'] = $arrs['card_id'];
            $data['code'] = $arrs['code'];
            $data['bonus'] = $ruleinfo['reward_bonus'];
            $data['record_bonus'] = '分享有礼';
            $res = $this->synuser($data);
            $CardUserGet = new CardUserGet();
            $CardUserGet->where(['code'=>$arrs['code'],'card_id'=>$arrs['card_id']])->setField('bonus', $res['result_bonus']);
            return $data;
        }

    }

    //分享领取奖励余额
    public function getsharebalance($arrs){

        $CardShareRule = new CardShareRule();
        $ruleinfo = $CardShareRule->where(['id'=>$arrs['rule_id']])->find();
        if ($ruleinfo['reward_balance'] > 0) {
            $CardUserGet = new CardUserGet();
            $map['card_id'] = $arrs['card_id'];
            $map['code'] = $arrs['code'];
            $CardUserGet->where($map)->setInc('balance',$ruleinfo['reward_balance']);
            $data['card_id'] = $arrs['card_id'];
            $data['type'] = 4;
            $data['openid'] = $arrs['openid'];
            $data['add_balance'] = $ruleinfo['reward_balance'];
            $data['balance'] = $CardUserGet->where(['code'=>$arrs['code'],'card_id'=>$arrs['card_id']])->value('balance');
            $data['tplmesg_info'] = $this->balancesendmesg($data);
            return $data;
        }
    }

    //群发投放
    public function massputcard($arr){
        $map['mid'] = $arr['mid'];
        $CardPutRule = new CardPutRule();
        $cardid = $CardPutRule->where($map)->value('card_id');
        $data = [
            "touser"=>[
                $arr['openid']
            ],
            "wxcard"=>[
                "card_id"=>$cardid
            ],
            "msgtype"=>"wxcard",
        ];
        //配置注入
        $mid = $map['mid'];
        $options = $this->option($mid);
        $wxObj = new Wxobjopen($options);
        $wxObj->mesgSend($data);
    }

    //客服消息投放
    public function mesgputcard($arr){
        $map['mid'] = $arr['mid'];
        $CardPutRule = new CardPutRule();
        $cardid = $CardPutRule->where($map)->value('card_id');
        $data = [
            "touser"=>$arr['openid'],
            "wxcard"=>[
                "card_id"=>$cardid
            ],
            "msgtype"=>"wxcard",
        ];
        //配置注入
        $mid = $map['mid'];
        $options = $this->option($mid);
        $wxObj = new Wxobjopen($options);
        $wxObj->custMesg($data);
    }


    //判断激活状态并停止
    private function checkfire($arr){
        $CardUserGet = new CardUserGet();
        $user = $CardUserGet->where($arr)->field('fire')->find();
        if ($user['fire'] == 1){
            return '001';
            exit();
        }
    }

    //激活
    public function userfirecard($datas){
        $map['card_id'] =  $datas['cardid'];
        $map['code'] = $datas['usercardcode'];
        $res = $this->checkfire($map);
        return $res;
        //获取会员填写激活信息
        $arr = array(
            'card_id'=>$datas['cardid'],
            'code'=>$datas['usercardcode']
        );
        //获取会员填写信息
        $info = $this->getfireinfo($arr);
        if ($info['errcode'] == 0){
            $CardUserGet = new CardUserGet();
            $udata = $this->fillgetinfo($info);
            //同步积分
            $CardMember = new CardMember();
            //该卡信息
            $card = $CardMember->where('card_id',$map['card_id'])->field('syn_is_exist,supply_bonus')->find();

            if ($card['supply_bonus'] == 1){
                $udata['bonus'] = $this->getcardbonus($datas['cardid']);
                $datass['add_bonus'] = $udata['bonus'];
                $datass['card_id'] = $arr['card_id'];
                $datass['openid'] = $CardUserGet->where($arr)->value('openid');
                $datass['code'] = $datas['usercardcode'];
                $datass['con_username'] = '激活赠送';
                $datass['record_bonus'] = '激活赠送';
                $datass['hx_fs'] = '激活赠送';
                $datass['type'] = 3;
                $datass['create_time'] = time();
                $datass['mid'] = $this->getmid($arr['card_id']);
                $CardUserUpdate = new CardUserUpdate();
                $CardUserUpdate->allowField(true)->save($datass);

            }
            //会员填写信息更新存入USERGET表
            if (isset($udata['fireinfo']) && isset($udata['fireinfo']['实体卡号'])){
                $fireinfo = json_decode($udata['fireinfo'],true);
                $udata['old_code'] = $fireinfo['实体卡号'];
            }
            $CardUserGet->allowField(true)->save($udata,['card_id'=>$map['card_id'],'code'=>$map['code']]);
            //分享奖励
            $arrshare['card_id'] = $arr['card_id'];
            $arrshare['outerstr'] = $CardUserGet->where(['card_id'=>$map['card_id'],'code'=>$map['code']])->value('outerstr');
            $arrshare['type'] = 'firecard';
            $arrshare['get_code'] = $datas['usercardcode'];
            $arrshare['get_openid'] = $datas['openid'];
            $share = $this->shareget($arrshare);
            //获取mid
            $mid = $this->getmid($arr['card_id']);
            //同步会员数据
            //判断同步
            if ($card['syn_is_exist'] <> 0) {
                $CardLeaduser = new CardLeaduser();
                //手机号为条件
                if ($card['syn_is_exist'] == 1) {
                    $synuser = $CardLeaduser->where(['phone' => $udata['phone'], 'mid' => $mid])->find();
                    //是否已被同步
                    if ($synuser['statu'] == 1){
                        return 1;
                    }
                }else{
                    //旧卡号为条件
                    $fireinfo = json_decode($udata['fireinfo'],true);
                    $udata['old_code'] = $fireinfo['实体卡号'];
                    $synuser = $CardLeaduser->where(['old_code' => $udata['old_code'], 'mid' => $mid])->find();
                    //是否已被同步
                    if ($synuser['statu'] == 1){
                        exit();
                    }
                }
                if (isset($synuser) && $synuser['statu'] == 0) {
                    $sdata = [
                        'code' => $datas['usercardcode'],
                        'card_id' => $datas['cardid'],
                        'bonus' => $synuser['bonus'],
                        'balance' => $synuser['balance'],
                        'openid' => $datas['openid'],
                        'record_bonus' => '同步奖励',
                    ];
                    $synres = $this->synuser($sdata);
                    $synresb = $this->leaduserbalance($sdata);


                    if ($synres['errcode'] == 0) {
                        //存入核销表
                        $cdata['card_id'] = $datas['cardid'];
                        $cdata['code'] = $datas['usercardcode'];
                        $cdata['add_bonus'] = $synuser['bonus'];
                        $cdata['add_balance'] = $synuser['balance'];
                        $cdata['openid'] = $datas['openid'];
                        $cdata['mid'] = $mid;
                        $cdata['con_username'] = '同步';
                        $cdata['record_balance'] = '同步';
                        $cdata['record_bonus'] = $sdata['record_bonus'];
                        $cdata['hx_fs'] = '同步';
                        $cdata['create_time'] = time();

                        if (isset($synresb['tplmesg_info'])) {
                            $cdata['tplmesg_info_zs'] = json_encode($synresb['tplmesg_info']);
                        }

                        $CardUserUpdate = new CardUserUpdate();

                        $CardUserUpdate->allowField(true)->save($cdata);

                        //更新USERGET表

                        $bdata['bonus'] = $synres['result_bonus'];

                        if (isset($udata['old_code'])){
                            $bdata['old_code'] = $udata['old_code'];
                        }
                        $where['card_id'] = $cdata['card_id'];
                        $where['code'] = $cdata['code'];
//                        return $where;
                        $res = $CardUserGet->allowField(true)->save($bdata, $where);
                        if ($res) {
                            $ldata['statu'] = 1;
                            $ldata['update_time'] = time();
                            $ldata['new_code'] = $datas['usercardcode'];
                            $wherel['id'] = $synuser['id'];
                            $CardLeaduser->allowField(true)->save($ldata,$wherel);
                        }else{
                            $res = 6;
                        }
                        return $res;
                    }else{
                        return 2;
                    }
                }else{
                    return 3;
                }
            }else{
                return 4;
            }
        }else{
            return 5;
        }
    }

    //查询激活信息
    public function getfireinfo($data){
        $options = $this->option($data['card_id']);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->userGetInfo($data);
        return $res;
    }

    //激活填写数据的处理
    public function fillgetinfo($info){
        $param = $info['user_info']['common_field_list'];
        foreach ($param as $k => $v) {
            switch ($v['name']) {
                case "USER_FORM_INFO_FLAG_MOBILE":
                    $arr['phone'] = $v['value'];
                    break;
                case "USER_FORM_INFO_FLAG_LOCATION":
                    if (isset($v['value'])) {
                        $arr['address'] = $v['value'];
                    }else{
                        $arr['address'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_BIRTHDAY":
                    if (isset($v['value'])) {
                        $arr['birthday'] = $v['value'];
                    }else{
                        $arr['birthday'] ='';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_NAME":
                    if (isset($v['value'])) {
                        $arr['name'] = $v['value'];
                    }else{
                        $arr['name'] ='';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_IDCARD":
                    if (isset($v['value'])) {
                        $arr['idnumber'] = $v['value'];
                    }else{
                        $arr['name'] ='';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_EMAIL":
                    if (isset($v['value'])) {
                        $arr['email'] = $v['value'];
                    }else{
                        $arr['name'] ='';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_EDUCATION_BACKGRO":
                    if (isset($v['value'])) {
                        $arr['backgro'] = $v['value'];
                    }else{
                        $arr['name'] ='';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_INDUSTRY":
                    if (isset($v['value'])) {
                        $arr['industry'] = $v['value'];
                    }else{
                        $arr['name'] ='';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_INCOME":
                    if (isset($v['value'])) {
                        $arr['income'] = $v['value'];
                    }else{
                        $arr['name'] ='';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_HABIT":
                    if (isset($v['value'])) {
                        $arr['habit'] = $v['value'];
                    }else{
                        $arr['name'] ='';
                    }
                    break;
            }
        }
        if (isset($info['user_info']['custom_field_list'])){
            foreach ($info['user_info']['custom_field_list'] as $k=>$v){
                $userinfo[$v['name']] =  $v['value'];
            }
            if (isset($userinfo)) {
                $arr['fireinfo'] = json_encode($userinfo, JSON_UNESCAPED_UNICODE);
                if (isset($userinfo['实体卡号'])){
                    $arr['old_code'] = $userinfo['实体卡号'];
                }
            }
        }
        $arr['nickname']=$info['nickname'];
        $arr['sex'] = $info['sex'] == 'MALE'?1:0;
        $arr['fire'] = 1;
        return $arr;
    }

    //获取会员卡初始信息
    public function getcardbonus($arr){
        $CardMember = new CardMember();
        $card = $CardMember->where('card_id',$arr)->value('bonus_rule');
        $card = json_decode($card,true);
        $int_bonus = $card['init_increase_bonus'];
        return $int_bonus;
    }

    //同步传入积分
    public function synusers($arr){
        $data['code'] = $arr['code'];
        $data['card_id'] = $arr['card_id'];
        $data['record_bonus'] = $arr['record_bonus'];
        $data['add_bonus'] = $arr['bonus'];
        $data['notify_optional']['is_notify_bonus'] = true;
        $options = $this->option($arr['card_id']);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->updateUserInfo($data);
        return $res;
    }

    //同步传入积分
    public function synuser($arr){
        $data['code'] = $arr['code'];
        $data['card_id'] = $arr['card_id'];
        $data['record_bonus'] = $arr['record_bonus'];
        $data['add_bonus'] = $arr['bonus'];
        $data['notify_optional']['is_notify_bonus'] = true;
        $options = $this->option($arr['card_id']);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->updateUserInfo($data);
        return $res;
    }

    //同步奖励余额
    public function leaduserbalance($arrs){
        if ($arrs['balance'] > 0) {
            $CardUserGet = new CardUserGet();
            $map['card_id'] = $arrs['card_id'];
            $map['code'] = $arrs['code'];
            $CardUserGet->where($map)->setInc('balance',$arrs['balance']);
            $data['card_id'] = $arrs['card_id'];
            $data['type'] = 5;
            $data['openid'] = $arrs['openid'];
            $data['add_balance'] = $arrs['balance'];
            $data['balance'] = $CardUserGet->where(['code'=>$arrs['code'],'card_id'=>$arrs['card_id']])->value('balance');
            $data['tplmesg_info'] = $this->balancesendmesg($data);
        }else{
            $data['errcode'] = 9001;
        }
        return $data;
    }

    //删除
    public function userdelcard($datas){
        $map['openid'] = $datas['openid'];
        $map['card_id'] = $datas['card_id'];
        $map['code'] = $datas['code'];
        $data['update_time'] = $datas['create_time'];
        $data['have'] = 0;
        $CardUserGet = new CardUserGet();
        $cardtype = $CardUserGet->where('card_id',$datas['card_id'])->value('card_type');
        if ($cardtype == 'MEMBER_CARD'){
            $CardUserGet->where($map)->update($data);
        }else{
            $CardUserGet->where($map)->update($data);
        }
    }



    //核销
    public function userconsumecard($datas){
        //修改卡券状态
        $map['openid'] = $datas['FromUserName'];             //openid
        $map['card_id'] = $datas['CardId'];            //card_id
        $map['code'] = $datas['UserCardCode'];         //code
        $data['statu'] = 2;
        $CardUserGet = new CardUserGet();
        $CardUserGet->save($data,$map);
    }

    //更新
    public function userupdatecard($datas){
        $data['mid'] = 1;
        $data['openid'] = $datas['openid'];
        $data['card_id'] = $datas['cardid'];
        $data['code'] = $datas['code'];
        $data['add_bonus'] = $datas['modifybonus'];
        $data['add_balance'] = $datas['modifybalance'];
        $data['creattime'] = time();
        $data['type'] = 1;
        $data['source'] = json_encode($datas);
        $CardUserUpdate = new CardUserUpdate();
        $CardUserUpdate->save($data);
    }

    //库存报警
    public function userskucard($datas){
        $map['card_id'] = $datas['cardid'];
        $CardMerber = new CardMember();
        $CardGeneral = new CardGeneral();
        $only = $CardMerber->where($map)->value('id');
        if (empty($only)){
            $CardGeneral->where($map)->setField('datail',$datas['detail']);
        }else{
            $CardMerber->where($map)->setField('datail',$datas['detail']);
        }
    }


    //投放
    public function put($card_id){
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->option($card_id);
        $wxObj = new Wxobjopen($options);
        $noncestr = $wxObj->generateNonceStr();
        $res['config'] = $wxObj->getJsSign($url,'',$noncestr);
        $res['config']['debug'] = true;
        $res['config']['jsApiList'] = array('addCard','openCard','chooseCard');
        $res['addcard'] = $wxObj->wxAddCard($card_id,$noncestr);
        return $res;
    }

    //生成二维码
    public function qrcode($arr){
        $Qrcodes = new Qrcodes();
        $res = $Qrcodes->cardqrcode($arr);
        if ($res){
            return $res;
        }else{
            $res = '0';
            return $res;
        }
    }

    //JSSDK投放
    public function jssdk($type,$arr=''){
        $options = $this->option($arr);
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $wxObj = new Wxobjopen($options);
        if ($type == 0){
            $res = $wxObj->getJsSign($url);
            return $res;
        }
        if ($type == 1){
            $res = $wxObj->getJsSign($url);
            return $res;
        }
    }


    //接收客户端信息
    public function getCashier($arr){
        $map['mid'] = $arr['mid'];  //商户ID
        $map['openid'] = $arr['openid'];    //openid
        $CardMember = new CardMember();
        $CardUserGet = new CardUserGet();
        $cardid = $CardMember->where($map)->value('card_id');    //card_id
        //更新数据
        $data = [
            'bonus' => $arr['bonus'],
            'balance' => $arr['balance'],
        ];
        $res = $CardUserGet->where('card_id='.$cardid)->update($data);
        //判断输出
        if ($res == false){
            echo "成功";
        }else{
            echo "失败";
        }
    }

    //关注
    public function getfansinfo($datas){
        $openid = $datas['openid'];
        $CardFans = new CardFans();
        $map['openid'] = $openid;
        $map['gh_id'] = $datas['gh_id'];
        $isone = $CardFans->where($map)->value('id');
        //老用户重新关注
        if (isset($isone)){
            $option = $this->options($datas['gh_id']);
            $WxObj = new Wxobjopen($option);
            $user = $WxObj->getUserInfo($openid);
            $data['nickname'] = $user['nickname'];
            $data['head_url'] =$user['headimgurl'];
            $data['statu'] = 1;
            $data['update_time'] = time();
            $CardFans->allowField(true)->save($data,$map);
            //从未关注新用户
        }else{
            $option = $this->options($datas['gh_id']);
            $WxObj = new Wxobjopen($option);
            $users = $WxObj->getUserInfo($openid);
            $WxOpen = new WxOpen();
            $wx_open_id = $WxOpen->where('gh_id',$datas['gh_id'])->value('id');
            $data['wx_open_id'] = $wx_open_id;
            $data['gh_id'] = $datas['gh_id'];
            $data['statu'] = $users['subscribe'];
            $data['openid'] = $users['openid'];
            $data['nickname'] = $users['nickname'];
            $data['sex'] = $users['sex'];
            $data['city'] = $users['city'];
            $data['head_url'] =$users['headimgurl'];
            $data['province'] = $users['province'];
            $data['groupid'] = $users['groupid'];
            $data['create_time'] = time();
            $CardFans->allowField(true)->save($data);
        }
    }

    //取关
    public function offfansinfo($datas){
        $CardFans = new CardFans();
        $map['gh_id'] = $datas['gh_id'];
        $map['openid'] = $datas['openid'];
        $data['statu'] = 2;
        $data['update_time'] = time();
        $res = $CardFans->allowField(true)->save($data,$map);
    }

    //模版消息yue
    public function balancesendmesg($arr){
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $map['id'] = $CardMember->where('card_id',$arr['card_id'])->value('mid');
        $wx_open_id = $Merchant->where($map)->value('wx_open_id');
        //初始化微信类
        $options = $this->option($arr['card_id']);
        $wxObj = new Wxobjopen($options);
        $OpenTemplate= new OpenTemplate();
        $templateid=$OpenTemplate->where(['type'=>'card_ye_tpl','wx_open_id'=>$wx_open_id])->value('template_id');
        switch ($arr['type']) {
            case "1":
                $type = "充值";
                break;
            case "2":
                $type = "消费";
                break;
            case "3":
                $type = "奖励";
                break;
            case "5":
                $type = "同步";
                break;
            default:
                $type = "未知";
                break;
        }
        $add_balance = floor($arr['add_balance']*100)/100;
        $balance = floor($arr['balance']*100)/100;
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => trim($templateid),
            'url' => "",
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => '余额' . $type . "提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'keyword2' => ['value' => '余额' . $type, 'color' => '#FF0000'],
                'keyword3' => ['value' => $add_balance.'元', 'color' => '#000'],
                'keyword4' => ['value' => $balance.'元','color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $wxObj->sendTemplateMessage($template);
        return $res;
    }

    //微信API参数
    public function options($gh_id){
        Session::set('openid', null);
        $System=new System();
        $WxOpen=new WxOpen();
        $Agent=new Agent();
        $mab['gh_id'] = $gh_id;
//        $config =$System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $config=$Agent->where(array('wx_open_id'=>$users['id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //微信API参数
    public function option($card_id){
        Session::set('openid', null);
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $System=new System();
        $WxOpen=new WxOpen();
        $Agent=new Agent();
        $map['id'] = $CardMember->where('card_id',$card_id)->value('mid');
        $merchantinfo= $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config =$System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $config=$Agent->where(array('id'=>$merchantinfo['agent']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }


}